<?php
chdir("/home/cm/public_html/crons/");
include('../config.php');

$db_obj = new db_obj();
$task_obj = new task_obj();
$notify_obj = new notify_obj();
$user_obj = new user_obj();
$log = new Logging();

$log->lfile('../logs/task_notifications_' . date('Y_m_d') . '.log');
$log->lwrite('Vyberam tasky, ktore sa budu notifikovat:');

$filter = array();
$filter['task_start'] = date("Y-m-d");
$tasks = $task_obj->getListOfTasks($filter);
$log->lwrite('------------------------------------------');
if (error_obj::isError($tasks))
    $log->lwrite ("ERROR - zlyhalo nacitanie taskov");
elseif(empty($tasks))
    $log->lwrite ("WARNING - ziadny task sa nenotifikuje");
else {
    foreach ($tasks as $i => $task) {
        $log->lwrite ("TaskId: " . $task['taskId'] . ", Title: " . $task['title']);   
        
        $recipients = array();
        
        if (!empty($task['responsible'])) {
            $responsible = $user_obj->getUserById($task['responsible']);
            if (error_obj::isError($responsible))
                $log->lwrite ("ERROR - zlyhalo nacitanie responsible");
            elseif (empty($responsible))
                $log->lwrite ("WARNING - responsible neexistuje");
            else {
                $recipients[] = $responsible['email'];
                $log->lwrite ("Email prijemcu: " . $responsible['email']);
            }
        }
        
        if (!empty($task['worker'])) {
            $worker = $user_obj->getUserById($task['worker']);
            if (error_obj::isError($worker))
                $log->lwrite ("ERROR - zlyhalo nacitanie worker");
            elseif (empty($responsible))
                $log->lwrite ("WARNING - worker neexistuje");
            else {
                $recipients[] = $worker['email'];
                $log->lwrite ("Email prijemcu: " . $worker['email']);
            }
        }
        $message = 'Today it is necessary to begin to solve this task: <a href="'.WWW.'?input=edit_task&task='.$task['taskId'].'">'.$task['title'].'</a>.';
        $subject = 'CM: Start date of task - ' . $task['title'];
        
        $result = $notify_obj->send($recipients, $message, $subject);
        
        if (error_obj::isError($result))
            $log->lwrite ("ERROR - zlyhalo odoslanie notifikacii");
        else
            $log->lwrite ("Notifikacie boli odoslane");
        
    }
}
$log->lwrite('------------------------------------------');

$log->lclose();
?>
